<template>
  <div class="app-container">
    <el-row>
      <el-col :span="8" :xs="24" class="leftTransfer">
        <el-transfer
          v-model="transferModel"
          :left-default-checked="[]"
          :right-default-checked="[]"
          :render-content="renderFunc"
          :titles="['未获得权限', currentName]"
          :button-texts="['删除', '添加']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          :data="transferData"
          style="text-align: left; display: inline-block"
          @change="transferChange"/>
      </el-col>

      <el-col :span="13" :xs="24">
        <!--页头-->
        <div class="filter-container">
          <el-input
            :placeholder="'角色名称'"
            v-model="listQuery.name_LIKE"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"/>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            搜索
          </el-button>
          <el-button v-waves class="filter-item" type="primary" icon="reset" @click="resetCondition">
            <svg-icon icon-class="reset"/>
            重置
          </el-button>
          <el-button
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            icon="el-icon-edit"
            @click="handleCreate">添加
          </el-button>
          <el-button
            v-waves
            :loading="downloadLoading"
            class="filter-item"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete">删除
          </el-button>
        </div>

        <!--table主体-->
        <el-table
          v-loading="listLoading"
          ref="table"
          :key="tableKey"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column width="33" type="selection" align="center" />
          <el-table-column :label="'角色名'" align="center" fixed>
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="'备注'" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.name!=='admin'" type="primary" size="mini" @click="findPermissionIdByRoleId(scope.row.id,scope.row.name)">
                权限编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--分页组件-->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"/>

        <!--弹框-->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" :model="temp" label-position="left" style="margin-left:8px;">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="temp.name" clearable/>
            </el-form-item>
            <el-row :gutter="5">
              <el-col :span="24" :xs="24">
                <el-form-item label="备注">
                  <el-input type="textarea" v-model="temp.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
            <el-button type="primary" @click="createData">{{ $t('table.confirm') }}
            </el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { fetchList, modify, remove, findTransferAll, findPermissionIdByRoleId, addPermission,add } from '@/api/role.js'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import AutoSelect from '@/components/AutoSelect'

export default {
  name: 'ProductList',
  components: { Pagination, AutoSelect },
  directives: { waves },
  data() {
    return {
      currentId: null,
      currentName: '---',
      transferData: [], // 所有权限
      transferModel: [], // 已有权限key
      renderFunc(h, option) {
        return <span > {option.label} < /span>
      },
      tableKey: 0,
      list: null, // 主体数据
      total: 0, // 总条数
      listLoading: true, // 是否加载中
      listQuery: { // 查询条件
        page: 1,
        limit: 10
      },
      temp: {},   // 临时缓存数据
      dialogFormVisible: false, // 是否弹窗
      dialogStatus: '', // 当前弹窗
      textMap: { //  弹窗类型
        create: '添加角色'
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.findTransferAll()
  },
  methods: {
    findPermissionIdByRoleId(id, name) {
      findPermissionIdByRoleId(id).then(response => {
        if (response.success) {
          this.currentId = id
          this.currentName = name
          this.transferModel = response.data
        }
      })
    },
    // 数据变更
    transferChange(value, direction, movedKeys) {
      if (this.currentId == null) {
        this.$message.error('请选择角色!')
        return
      }
      var arr = movedKeys.join(',')
      addPermission({
        direction: direction,
        ids: arr,
        roleId: this.currentId
      }).then(rep => {
        if (!rep.success) {
          this.$message.error('操作失败!')
        }
      })
    },
    // 重置搜索框
    resetCondition() {
      this.listQuery.name_LIKE = ''
      this.getList()
    },
    // 获得全部权限地址
    findTransferAll() {
      findTransferAll().then(response => {
        if (response.success) {
          this.transferData = response.data
        }
      })
    },
    // 删除
    handleDelete() {
      var ids = ''
      this.$refs.table.selection.forEach(function(row) {
        if (ids !== '') {
          ids += ','
        }
        ids += row.id
      })
      if (ids === '') {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据!'
        })
        return
      }
      this.$confirm('删除后不可恢复，是否确认删除?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(ids).then((response) => {
          if (response.success) {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message.error('删除失败!')
          }
        })
      })
    },
    // 获得数据
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.rows
        this.total = response.total
        this.listLoading = false
      })
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 更新数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          modify(this.temp).then((response) => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.temp).then((response) => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    // 创建页面
    handleCreate() {
      this.temp = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    }
  }
}
</script>
<style scoped>
  .leftTransfer {
    min-width: 530px;
  }

  img {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
  }
</style>
